import { request } from "../../request/index.js";
import { getSetting, chooseAddress, openSetting, showModal, showToast } from "../../utils/asyncWx.js"

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
    },
    TimeId: -1,

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        const userInfo = wx.getStorageSync("userInfo");
        this.setData({
            userInfo,
        })
    },

    // 点击 收获地址
    async handleChooseAddress() {
        try {
            // 1 获取 权限状态
            const res = await getSetting();
            const scopeAddress = res.authSetting["scope.address"];
            // 2 判断 权限状态 '现在无需判断'
            if (scopeAddress === false) {
                // 3 诱导用户打开授权页面
                await openSetting();
            }
            // 4 调用获取收获地址的 api
            const address = await chooseAddress();

            // 5 存入到缓存中
            wx.setStorageSync("address", address);
            wx.navigateBack({
                delta: 1
            });
        } catch (error) {
            console.error(error);
        }

    },

    handleUpdateInfo(e) {
        // 获取电话号码
        const { phone } = e.detail.value;
        if (!phone) {
            this.data.userInfo.phone_number = this.data.userInfo.phone_number;
        } else {
            this.data.userInfo.phone_number = phone;
        }
        // 获取邮箱地址
        const { email } = e.detail.value;
        if (!email) {
            this.data.userInfo.email = this.data.userInfo.email;
        } else {
            this.data.userInfo.email = email;
        }

        //检查电话
        if (phone && (!(/^[1][3,4,5,7,8][0-9]{9}$/).test(phone))) {
            showToast({ title: "请输入合法的电话", icon: "none" });
            return;
        }
        //检查邮箱
        if (email && !((/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/).test(email))) {
            showToast({ title: "请输入正确格式的邮箱地址", icon: "none" });
            return;
        }
        const modifyParams = {
            openId: this.data.userInfo.open_id,
            email: this.data.userInfo.email,
            phone_number: this.data.userInfo.phone_number
        }
        request({ url: "/user/modifyWUser", data: modifyParams, method: "POST" });

        wx.setStorageSync("userInfo", this.data.userInfo);
        showToast({ title: "修改成功", icon: "success" });
        setTimeout(function() {
            wx.navigateBack({
                delta: 1
            });
        }, 1000);
    }

})